package com.zhihuichongcheng.application.ui;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.controller.EaseUI;
import com.smartlib.cmnObject.util.FileUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.smartlib.cmnObject.util.SPUtil;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.im.DemoApplication;
import com.zhihuichongcheng.application.im.DemoHelper;

import java.io.File;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


/**
 * Created by admin on 16/7/21.
 */
public class BaseApplication extends DemoApplication {
    public static final String APP_ID = "2882303761517544225";
    public static final String APP_KEY = "5741754421225";
    private static DemoHandler sHandler = null;
    private OSS oss;
    private List<Activity> mList = new LinkedList();
    private UserBean mUser;
    private EaseUI easeUI;

    @Override
    public void onCreate() {
        super.onCreate();
        DemoHelper.getInstance().init(applicationContext);
        initEtc();
        configDownLoadPath();
        configOSS();
        if (shouldInit()) {
            MiPushClient.registerPush(this, APP_ID, APP_KEY);
        }
        if (sHandler == null) {
            sHandler = new DemoHandler(getApplicationContext());
        }
        File dir = new File(Constants.Const_Cache_Dir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

    }

    private void initEtc() {
        EMOptions options = new EMOptions();
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        // 如果APP启用了远程的service，此application:onCreate会被调用2次
        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        // 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回

        if (processAppName == null || !processAppName.equalsIgnoreCase(this.getPackageName())) {
            Log.e("feng", "enter the service process!");

            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
        //初始化
        EaseUI.getInstance().init(this, options);
        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(true);
    }

    private void configDownLoadPath() {
        try {
            LogUtil.logI(FileUtil.getRootPath());
            File file = new File(Constants.Const_Cache_Dir);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void configOSS() {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Constants.OSS_ACCESS_KEY_ID,
                Constants.OSS_ACCESS_KEY_SECRET);
        oss = new OSSClient(getApplicationContext(), Constants.OSS_ENDPOINT, credentialProvider);
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    public UserBean getUser() {
        SPUtil spUtil = SPUtil.getInstance(this);
        String value = spUtil.getString("user");
        mUser = GsonUtil.praseFromStringToBean(value, UserBean.class);
        return mUser;
    }

    public void setUser(UserBean user) {
        this.mUser = user;
    }

    public OSS getOss() {
        return oss;
    }

    public void setOss(OSS oss) {
        this.oss = oss;
    }

    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    public void exit() {
        try {
            for (int i = mList.size() - 1; i >= 0; i--) {
                Activity activity = mList.get(i);
                if (activity != null) {
                    activity.finish();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    public void removeActivity(Activity activity) {
        mList.remove(activity);
    }

    public void loginOut() {
        EMClient.getInstance().logout(false, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                LogUtil.logD("登录聊天服务器失败！" + code + message);
            }
        });
    }

    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        super.onTerminate();
    }

    public static class DemoHandler extends Handler {

        private Context context;

        public DemoHandler(Context context) {
            this.context = context;
        }

        @Override
        public void handleMessage(Message msg) {
            String s = (String) msg.obj;
            LogUtil.logD("ssss" + s);
            if (!TextUtils.isEmpty(s)) {
                Toast.makeText(context, s, Toast.LENGTH_LONG).show();
            }
        }
    }

}
